<template>
  <BaseContainer :show-title="false" class="main">
    <a-spin :spinning="loading">
      <a-descriptions size="small" :column="3" class="main__descriptions">
        <template #title>
          <span @click="handleBack" class="cursor-pointer">
            <arrow-left-outlined class="inline-block leading-0 ft-16 mr-2" />
            <span class="inline-block mb-0 font-bold ft-16">
              {{ `词包ID：${detailInfo.orderId ?? ''}` }}
            </span>
          </span>
        </template>
        <a-descriptions-item v-if="hasPermission([OPERATION])" label="投放账号">{{
          detailInfo.serviceUserName
        }}</a-descriptions-item>
        <a-descriptions-item label="审核状态（计划）">{{ transformMovedStatus(detailInfo) }}</a-descriptions-item>
        <a-descriptions-item label="上线状态">{{ ServiceStatusKeyMap[detailInfo.serviceStatus] }}</a-descriptions-item>
        <a-descriptions-item label="订单时长">{{ detailInfo.days }}</a-descriptions-item>
        <a-descriptions-item label="创建时间">{{ detailInfo.createTime }}</a-descriptions-item>
        <a-descriptions-item label="剩余天数">{{ detailInfo.remainDays }}</a-descriptions-item>
        <a-descriptions-item label="推广时段">
          <span v-if="BW || BWYXB">{{ detailInfo.onLinePeriod }}</span>
          <span v-else>7*24小时</span>
        </a-descriptions-item>
        <a-descriptions-item label="投放区域" v-if="BW || BWYXB || BWSD || BWSDYXB">
          <area-popover ellipsis :areas="detailInfo.areas" :product-id="detailInfo.productId" />
        </a-descriptions-item>
        <a-descriptions-item label="投放区域" v-else>全国</a-descriptions-item>
        <a-descriptions-item label="上线时间">{{
          formatDate(detailInfo.serviceTime, 'YYYY-MM-DD') || '--'
        }}</a-descriptions-item>
        <a-descriptions-item label="到期时间">{{
          formatDate(detailInfo.expireTime, 'YYYY-MM-DD') || '--'
        }}</a-descriptions-item>
      </a-descriptions>
    </a-spin>

    <Divider />
    <TableToolbar title="已选关键词">
      <ExportExcel :col="columns" :data="detailInfo?.creatives ?? []">
        <template #default="{ exportExcel }">
          <a-button @click="handleExportExcel(exportExcel)">
            <template #icon><download-outlined /></template>
            导出Excel
          </a-button>
        </template>
      </ExportExcel>
    </TableToolbar>
    <a-table
      :pagination="false"
      row-key="frontKey"
      :columns="columns"
      :loading="loading"
      :data-source="detailInfo.creatives || []"
      :scroll="{ y: 860, x: 1000 }"
    >
      <template #bodyCell="{ column, record, text }">
        <template v-if="column.key === 'word'">
          <a-input
            v-model:value="editableData[record.orderWordId][column.dataIndex]"
            v-if="editableData[record.orderWordId]"
          />
          <span v-else>
            {{
              record.type === WordTypeEnum.Zhzc
                ? `${text}（组）`
                : record.type === WordTypeEnum.Zxzc
                  ? `${text}（赠）`
                  : text
            }}
          </span>
        </template>
        <template v-if="column.key === 'clientType'">
          <a-radio-group
            v-model:value="editableData[record.orderWordId][column.dataIndex]"
            v-if="
              editableData[record.orderWordId] &&
              (detailInfo.productId === ProductEnum.CiBao || detailInfo.productId === ProductEnum.CBYXB)
            "
          >
            <a-radio :value="PlatformEnum.PC">PC端</a-radio>
            <a-radio :value="PlatformEnum.MOBILE">移动端</a-radio>
          </a-radio-group>
          <span v-else>{{ PlatformKeyMap[record.clientType] }}</span>
        </template>
        <template v-if="column.key === 'serviceApproveStatus'">
          <a-tooltip placement="top" v-if="hasPermission([OPERATION])">
            <template #title v-if="record.serviceOfflineReasons">
              <span>{{ record.serviceOfflineReasons }}</span>
            </template>
            <span>{{ PromotionServiceApproveStatusKeyMap[text] }}</span>
          </a-tooltip>
          <a-tooltip placement="top" v-else>
            <template #title v-if="record.serviceApproveStatus === PromotionServiceApproveStatusEnum.Fail">
              <span>{{ record.serviceOfflineReasons }}</span>
            </template>
            <span>{{ promotionServiceApproveStatusAdapter(text) }}</span>
          </a-tooltip>
        </template>
        <template v-if="column.key === 'wordApproveStatus'">
          <a-tooltip placement="top" v-if="hasPermission([OPERATION])">
            <template #title v-if="record.wordOfflineReasons">
              <span>{{ record.wordOfflineReasons }}</span>
            </template>
            <span>{{ WordApproveStatusKeyMap[text || WordApproveStatusEnum.Waiting] }}</span>
          </a-tooltip>
          <a-tooltip placement="top" v-else>
            <template #title v-if="record.serviceApproveStatus === WordApproveStatusEnum.NotSuitable">
              <span>{{ record.wordOfflineReasons }}</span>
            </template>
            <span>{{ wordApproveStatusAdapter(text || WordApproveStatusEnum.Waiting) }}</span>
          </a-tooltip>
        </template>
        <template v-if="column.key === 'groupApproveStatus'">
          <span v-if="hasPermission([OPERATION])">{{
            GroupApproveStatusKeyMap[text || GroupApproveStatusEnum.Waiting]
          }}</span>
          <span v-else>{{ groupApproveStatusAdapter(text || GroupApproveStatusEnum.Waiting) }}</span>
        </template>
        <template v-if="column.key === 'operate'">
          <template v-if="OrderOperateEnum.editable === orderDetailOperate">
            <div v-if="editableData[record.orderWordId]">
              <a-popconfirm
                title="确定要提交吗？"
                :disabled="editableData[record.orderWordId].loading"
                @confirm="handleEditable(record.orderWordId)"
              >
                <a-button type="link" :disabled="editableData[record.orderWordId].loading" class="mr-2 p-0"
                  >确定</a-button
                >
              </a-popconfirm>
              <a-button
                type="link"
                :disabled="editableData[record.orderWordId].loading"
                class="p-0"
                @click="delete editableData[record.orderWordId]"
                >取消</a-button
              >
            </div>
            <a @click="handleChange(record)" v-else>修改</a>
          </template>
          <template v-else>
            <a-button danger class="mr-2" v-if="record.title" @click="handleCreative(record)">编辑创意</a-button>
            <a-button type="primary" class="mr-2" v-else @click="handleCreative(record)">添加创意</a-button>
            <a-button :disabled="!record.groupId" v-permission="[OPERATION]" @click="handleNegativeAddWithWord(record)"
              >添加否词</a-button
            >
          </template>
        </template>
      </template>
    </a-table>
  </BaseContainer>
  <promotion-negation
    class="mt-5-important"
    v-permission="[OPERATION]"
    :query-fields="queryFields"
    :loading="negativeLoading"
    :pagination="pagination"
    :keyword-options="detailInfo.creatives"
    :table-data="negativeWords.negativeWords"
    :on-delete="handleNegativeDelete"
    @on-add="handleNegativeAdd"
    @on-edit="handleNegativeEdit"
    @on-query="loadNegativeWords"
    @on-reset="handleNegativeReset"
  />
  <negation-updater
    :submitting="submitting"
    :mode="mode"
    :form-data="formData"
    :keyword-options="detailInfo.creatives"
    :campaign-ids="campaignIds"
    v-model:data="formFields"
    v-model:show="visible"
    @on-submit="handleNegativeSubmit"
  />
</template>

<script lang="ts" setup>
import { computed, onMounted, reactive } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { OrderOperateEnum, usePromotionStore } from '@/store/usePromotionStore'
import { message, type TableProps } from 'ant-design-vue'
import { ArrowLeftOutlined, DownloadOutlined } from '@ant-design/icons-vue'
import BaseContainer from '@/components/base-container/index.vue'
import TableToolbar from '@/components/table-toolbar/index.vue'
import ExportExcel from '@/components/export-excel/index.vue'
import Divider from '@/components/divider/index.vue'
import { cloneDeep, compact, pick } from 'lodash-es'
import updateOrderWord from '@/services/order/updateOrderWord'
import { useCategory } from '@/hooks/useCategotry'
import AreaPopover from '@/components/area-popover/index.vue'
import { hasPermission } from '@/utils/permission'
import getPromotionDetail from '@/services/promotion/getPromotionDetail'
import { formatDate } from '@/utils'
import type { Creative, Promotion } from '@/core/interfaces/promotion'
import type { PromotionServiceStatusEnum } from '@/core/enums/status'
import { GroupApproveStatusEnum, PromotionServiceApproveStatusEnum, WordApproveStatusEnum } from '@/core/enums/status'
import {
  GroupApproveStatusKeyMap,
  PromotionServiceApproveStatusKeyMap,
  PromotionServiceStatusKeyMap,
  ServiceStatusKeyMap,
  WordApproveStatusKeyMap
} from '@/core/mapper/status'
import { WordTypeEnum } from '@/core/enums/type'
import { PlatformEnum, ProductEnum } from '@/core/enums/platform'
import { PlatformKeyMap } from '@/core/mapper/platform'
import type { OrderKeyword } from '@/core/interfaces/keyword'
import { AuthEnum } from '@/core/enums/auth'
import { storeToRefs } from 'pinia'
import PromotionNegation from '@/views/promotion/components/PromotionNegation.vue'
import NegationUpdater from '@/views/promotion/components/NegationUpdater.vue'
import { useNegativeWords } from '@/views/promotion/hooks/useNegativeWords'
import type { CampaignIds } from '@/core/interfaces/campaign'
import { ScopeTypeEnum } from '@/core/enums/negative'
import { transformMovedStatus } from './utils'

const route = useRoute()
const router = useRouter()
const promotionStore = usePromotionStore()
const { orderDetailOperate } = storeToRefs(promotionStore)
const editableData = reactive<Record<Creative['orderWordId'], Creative & { loading?: boolean }>>({})
const { OPERATION } = AuthEnum
const adId = route.query.adId as string
const [, fetchOrderWord] = updateOrderWord()
const [detailInfo, fetchPromotionDetail, loading] = getPromotionDetail()
const productId = computed(() => detailInfo.value.productId!)
const { BW, BWYXB, BWSD, BWSDYXB } = useCategory(productId)
const {
  mode,
  visible,
  formFields,
  queryFields,
  formData,
  pagination,
  negativeWords,
  negativeLoading,
  submitting,
  loadNegativeWords,
  submitNegativeWords,
  handleNegativeAdd,
  handleNegativeEdit,
  handleNegativeDelete,
  handleNegativeReset,
  handleNegativeAddWithWord
} = useNegativeWords(detailInfo)
const campaignIds = computed<Partial<CampaignIds>>(() => {
  return pick(detailInfo.value, ['pcWapCampaignId', 'wapCampaignId', 'pcCampaignId'])
})
const columns = computed<TableProps['columns']>(() => {
  return compact([
    {
      title: '关键词ID',
      dataIndex: 'orderWordId',
      key: 'orderWordId',
      width: '150px'
    },
    {
      title: '关键词',
      dataIndex: 'word',
      key: 'word',
      width: '160px',
      customRender: ({ text, record }: { text: string; record: Creative }) => {
        return record.type === WordTypeEnum.Zhzc
          ? `${text}（组）`
          : record.type === WordTypeEnum.Zxzc
            ? `${text}（赠）`
            : text
      }
    },
    {
      title: '端口',
      dataIndex: 'clientType',
      key: 'clientType',
      width: '120px',
      filters: [
        { text: PlatformKeyMap[PlatformEnum.PC], value: PlatformEnum.PC },
        { text: PlatformKeyMap[PlatformEnum.MOBILE], value: PlatformEnum.MOBILE }
      ],
      onFilter: (value: any, record: Creative) => record.clientType === value
    },
    {
      title: '（创意）审核状态',
      dataIndex: 'serviceApproveStatus',
      key: 'serviceApproveStatus',
      width: '130px'
    },
    {
      title: '（单元）审核状态',
      dataIndex: 'groupApproveStatus',
      key: 'groupApproveStatus',
      width: '130px'
    },
    {
      title: '（关键词）审核状态',
      dataIndex: 'wordApproveStatus',
      key: 'wordApproveStatus',
      width: '150px'
    },
    {
      title: '投放状态',
      dataIndex: 'serviceStatus',
      key: 'serviceStatus',
      width: '150px',
      customRender: ({ text }: { text: PromotionServiceStatusEnum }) => {
        return PromotionServiceStatusKeyMap[text]
      }
    },
    {
      title: '操作',
      dataIndex: 'operate',
      key: 'operate',
      width: '210px',
      fixed: 'right'
    }
  ])
})
function handleExportExcel(exportExcel: Function) {
  if (!(detailInfo.value.creatives || []).length) {
    message.error('表格数据为空')
    return
  }

  exportExcel(`订单关键词${Date.now()}`, {
    clientType: (value: PlatformEnum) => PlatformKeyMap[value]
  })
}

async function handleEditable(id: OrderKeyword['id']) {
  const record = editableData[id]
  record.loading = true
  const [err] = await fetchOrderWord({
    orderId: detailInfo.value.orderId!,
    id: record.orderWordId,
    name: record.word,
    clientType: record.clientType
  })

  record.loading = false

  if (!err) {
    delete editableData[record.orderWordId]
    await loadPromotionDetail()
  } else {
    message.error(err.message)
  }
}

function handleCreative(record: Creative) {
  promotionStore.setCurrentPromotionData(detailInfo.value as Promotion)
  promotionStore.setCreatives(detailInfo.value.creatives ?? [])
  promotionStore.setCurrentOrderWordId(record.orderWordId)

  router.push({
    name: 'promotion-creative'
  })
}

function handleChange(record: Creative) {
  editableData[record.orderWordId] = cloneDeep(record)
}

async function loadPromotionDetail() {
  return await fetchPromotionDetail({
    adId
  })
}

async function handleNegativeSubmit() {
  // 如果是计划否词，那么关键词置空
  const params = cloneDeep(formFields.value)
  if (formFields.value.scopeType === ScopeTypeEnum.Plan) {
    params.keyword = ''
    params.orderWordId = undefined
  }

  const [err, res] = await submitNegativeWords(params, mode.value)
  if (!err) {
    message.success(res.data.msg)
    visible.value = false
    await loadNegativeWords()
    await loadPromotionDetail()
  }
}

function wordApproveStatusAdapter(text: WordApproveStatusEnum) {
  const { Waiting, UrlValid, Enable, NotSuitable, Activate, Approval } = WordApproveStatusEnum

  if ([Waiting, Activate].includes(text)) {
    return WordApproveStatusKeyMap[Waiting]
  } else if ([Approval, UrlValid].includes(text)) {
    return WordApproveStatusKeyMap[Approval]
  } else if ([NotSuitable].includes(text)) {
    return WordApproveStatusKeyMap[NotSuitable]
  } else {
    return WordApproveStatusKeyMap[Enable]
  }
}

function promotionServiceApproveStatusAdapter(text: PromotionServiceApproveStatusEnum) {
  const { All, Activate, Unreviewed, Approval, UrlValid, Enable, Pause, Invalid, Fail } =
    PromotionServiceApproveStatusEnum

  if ([All, Activate, Unreviewed].includes(text)) {
    return PromotionServiceApproveStatusKeyMap[All]
  } else if ([Approval, UrlValid].includes(text)) {
    return PromotionServiceApproveStatusKeyMap[Approval]
  } else if ([Enable, Pause, Invalid].includes(text)) {
    return PromotionServiceApproveStatusKeyMap[Enable]
  } else {
    return PromotionServiceApproveStatusKeyMap[Fail]
  }
}

function groupApproveStatusAdapter(text: GroupApproveStatusEnum) {
  const { Waiting, All, Normal, Pause, PromotePause, Unreviewed } = GroupApproveStatusEnum

  if ([PromotePause, Pause, Normal].includes(text)) {
    return GroupApproveStatusKeyMap[Normal]
  } else if ([Unreviewed, Waiting, All].includes(text)) {
    return GroupApproveStatusKeyMap[Waiting]
  }
}

function handleBack() {
  router.go(-1)
}

onMounted(async () => {
  if (adId) {
    const [err] = await loadPromotionDetail()
    if (!err) {
      await loadNegativeWords()
    }
  } else {
    router.replace('/promotion')
  }
})
</script>

<script lang="ts">
export default {
  name: 'PromotionDetail'
}
</script>

<style lang="scss" scoped>
.main {
  &__extra {
    min-width: 242px;
    margin-left: 88px;
  }

  .statistic {
    width: 220px;
    text-align: right;
  }

  &__descriptions {
    margin-bottom: -8px;

    ::v-deep(.ant-descriptions-item-content) {
      overflow: hidden;
      flex-grow: 1;
    }
  }
}

.seacher {
  width: 250px;
}
</style>
